﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Vit.Web.Models;

namespace Vit.AdminModule.Areas.Admin.Providers
{
    public class SqlTagProvider : Vit.Web.Providers.ITagProvider
    {
        private WebProvidersDb db = new WebProvidersDb();
        
        #region ITagProvider Members

        public IQueryable<Tag> GetTopTags(int count)
        {
            return db.Tags.OrderByDescending(o => o.Hits).Take(count);
        }

        public IQueryable<TagObject> GetTagObjects(string tag, int count)
        {
            return db.TagObjects.Where(o => o.TagName == tag).OrderByDescending(o => o.CreateDate).Take(count);
        }

        public void AddTags(string objectType, string objectId, string[] tags)
        {
            if (tags == null && tags.Length <= 0)
                return;
            AddTags(tags);
            foreach (var t in tags)
            {
                var tagObj = db.TagObjects.FirstOrDefault(o => o.TagName == t && o.ObjectType == objectType && o.ObjectId == objectId);
                if (tagObj == null)
                {
                    tagObj = new TagObject()
                    {
                        TagName = t,
                        ObjectType = objectType,
                        ObjectId = objectId,
                        CreateDate = DateTime.Now,
                        Creator = Vit.Web.PortalContext.Current.User.Account
                    };

                    db.TagObjects.Add(tagObj);
                }
            }
            db.SaveChanges();
        }

        public void AddTags(string[] tags)
        {
            if (tags == null && tags.Length <= 0)
                return;
            foreach (var t in tags)
            {
                var tag = db.Tags.FirstOrDefault(o => o.Name == t);
                if (tag == null)
                {
                    tag = new Tag()
                    {
                        Name = t,
                        Hits = 1,
                        CreateDate = DateTime.Now,
                        Creator = Vit.Web.PortalContext.Current.User.Account,
                        Deleted = false
                    };
                    db.Tags.Add(tag);
                }
            }
            db.SaveChanges();
        }

        #endregion

        #region IProvider Members

        public string Name
        {
            get { return "SqlTagProvider"; }
        }

        #endregion
    }
}